package com.stone.customer.console.config;

import com.stone.customer.console.config.properties.CommonThreadPoolProperties;
import com.stone.customer.console.config.properties.PointSyncThreadPoolProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 会员console线程池配置
 *
 * @author Mr_wenpan@163.com 2021/07/15 17:55
 */
@Configuration
@EnableConfigurationProperties({PointSyncThreadPoolProperties.class})
public class CustomerConsoleThreadpoolConfig {

    @Bean("pointSyncThreadPool")
    public ThreadPoolTaskExecutor pointSyncThreadPool(@Qualifier("pointSyncThreadPoolProperties") PointSyncThreadPoolProperties properties) {
        return initThreadPoolTaskExecutor(properties);
    }

    @Bean("receiverFromRedisTriggerPool")
    public ThreadPoolTaskExecutor receiverFromRedisTriggerPool(@Qualifier("pointSyncThreadPoolProperties") PointSyncThreadPoolProperties properties) {
        return initThreadPoolTaskExecutor(properties);
    }

    private ThreadPoolTaskExecutor initThreadPoolTaskExecutor(CommonThreadPoolProperties properties) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数量
        threadPoolTaskExecutor.setCorePoolSize(properties.getCorePoolSize());
        // 最大线程数量
        threadPoolTaskExecutor.setMaxPoolSize(properties.getMaxPoolSize());
        // 队列中最大任务数
        threadPoolTaskExecutor.setQueueCapacity(properties.getQueueCapacity());
        // 线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(properties.getThreadNamePrefix());
        // 线程空闲后最大空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        // 当到达最大线程数是如何处理新任务
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
}
